using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using VotingSystem.Data;
using VotingSystem.Models;
using System.Security.Claims;

namespace VotingSystem.Controllers
{
    [Authorize]
    public class QuestionOptionsController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly ILogger<QuestionOptionsController> _logger;

        public QuestionOptionsController(ApplicationDbContext context, ILogger<QuestionOptionsController> logger)
        {
            _context = context;
            _logger = logger;
        }

        // GET: QuestionOptions/Create
        public async Task<IActionResult> Create(int questionId)
        {
            var question = await _context.SurveyQuestions
                .Include(q => q.Survey)
                .FirstOrDefaultAsync(q => q.Id == questionId);

            if (question == null || question.Survey == null)
            {
                return NotFound();
            }

            // 检查是否是创建者
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (userId == null || question.Survey.CreatorId != userId)
            {
                return Forbid();
            }

            ViewBag.QuestionId = questionId;
            return View();
        }

        // POST: QuestionOptions/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("QuestionId,OptionText,Order")] QuestionOption option)
        {
            var question = await _context.SurveyQuestions
                .Include(q => q.Survey)
                .FirstOrDefaultAsync(q => q.Id == option.QuestionId);

            if (question == null || question.Survey == null)
            {
                return NotFound();
            }

            // 检查是否是创建者
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (userId == null || question.Survey.CreatorId != userId)
            {
                return Forbid();
            }

            if (ModelState.IsValid)
            {
                _context.Add(option);
                await _context.SaveChangesAsync();
                return RedirectToAction("Details", "Surveys", new { id = question.SurveyId });
            }

            ViewBag.QuestionId = option.QuestionId;
            return View(option);
        }

        // GET: QuestionOptions/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var option = await _context.QuestionOptions
                .Include(o => o.Question)
                    .ThenInclude(q => q.Survey)
                .FirstOrDefaultAsync(o => o.Id == id);

            if (option == null || option.Question == null || option.Question.Survey == null)
            {
                return NotFound();
            }

            // 检查是否是创建者
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (userId == null || option.Question.Survey.CreatorId != userId)
            {
                return Forbid();
            }

            return View(option);
        }

        // POST: QuestionOptions/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,QuestionId,OptionText,Order")] QuestionOption option)
        {
            if (id != option.Id)
            {
                return NotFound();
            }

            var question = await _context.SurveyQuestions
                .Include(q => q.Survey)
                .FirstOrDefaultAsync(q => q.Id == option.QuestionId);

            if (question == null || question.Survey == null)
            {
                return NotFound();
            }

            // 检查是否是创建者
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (userId == null || question.Survey.CreatorId != userId)
            {
                return Forbid();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(option);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!OptionExists(option.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction("Details", "Surveys", new { id = question.SurveyId });
            }

            return View(option);
        }

        // GET: QuestionOptions/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var option = await _context.QuestionOptions
                .Include(o => o.Question)
                    .ThenInclude(q => q.Survey)
                .FirstOrDefaultAsync(o => o.Id == id);

            if (option == null || option.Question == null || option.Question.Survey == null)
            {
                return NotFound();
            }

            // 检查是否是创建者
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (userId == null || option.Question.Survey.CreatorId != userId)
            {
                return Forbid();
            }

            return View(option);
        }

        // POST: QuestionOptions/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var option = await _context.QuestionOptions
                .Include(o => o.Question)
                    .ThenInclude(q => q.Survey)
                .FirstOrDefaultAsync(o => o.Id == id);

            if (option == null || option.Question == null || option.Question.Survey == null)
            {
                return NotFound();
            }

            // 检查是否是创建者
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (userId == null || option.Question.Survey.CreatorId != userId)
            {
                return Forbid();
            }

            _context.QuestionOptions.Remove(option);
            await _context.SaveChangesAsync();
            return RedirectToAction("Details", "Surveys", new { id = option.Question.SurveyId });
        }

        private bool OptionExists(int id)
        {
            return _context.QuestionOptions.Any(e => e.Id == id);
        }
    }
} 